
var widgetHotEntries = {

	MAX_TWEET_DISP_LEN: 24,

	data: null,

	create: function() {
		return $('<div/>', { 'class': 'topicWidget', id: 'hotentries' })
			.append(
				$('<div/>', { 'class': 'topicBoxHeader' })
				.append($('<h3/>', { 'class': 'topicWidgetHeader', text: 'ホッテントリ' }))
			).append(
				$('<div/>', { 'class': 'topicBox' })
				.append(
					$('<div/>', { 'class': 'topicLoading', text: 'Loading...' })
					.append($('<img/>', { src: '/img/loading.gif', id: 'loading' }))
				)
			);
	},

	load: function(json) {
		var entries = $('<ul/>', { 'class': 'topicBody' }), me = this;
		this.data = json.threads;
		$.each(this.data, function() {
			// Trim HTML tags and URLs.
			var tweet = this.tweet.replace(/<.*?>/g, '').replace(/https?:\/\/[\x21-\x7e]+/gi, '');
			entries.append(
				$('<li/>')
				.append(
					$('<div/>', { 'class': 'tweet' })
					.append(
						$('<a/>', {
							href: this.url,
							text: me.formatTweet(tweet, this.replyCount),
							title: tweet
						})
					)
				)
				.append(
					$('<div/>', { 'class': 'owner' })
					.append(
						$('<a/>', {
							href: '/_ui/core/userprofile/UserProfilePage?u='+this.accountId,
							text: this.name
						})
					)
				)
				.append(
					$('<div/>', {
						'class': 'updated',
						text: me.formatUpdated(this.updated)
					})
				)
				.hover(
					function() { $(this).addClass('hover'); },
					function() { $(this).removeClass('hover'); }
				)
			);
		});

		// Render updated time every minute.
		setInterval(function() {
			widgetHotEntries.renderUpdated.call(widgetHotEntries);
		}, 60*1000);

		return entries;
	},

	trimTweet: function(tweet) {
		var str = escape(tweet), pos = 0, len =0;
		for(var i = 0; i < str.length; ++i, ++pos, ++len) {
			if(str.charAt(i) == '%') {
				if(str.charAt(++i) == 'u') {
					i += 3;
					++pos;
				}
				++i;
			}
			if(pos >= this.MAX_TWEET_DISP_LEN) {
				return tweet.substr(0, len);
			}
		}
		return tweet;
	},

	format: function(format) {
		var args = Array.prototype.slice.call(arguments, 1);
		return format.replace(/\{(\d+)\}/g, function(x, i) {
			return args[i];
		});
	},

	formatTweet: function(tweet, replies) {
		return this.format('{0}... ({1})', this.trimTweet(tweet), replies);
	},

	formatUpdated: function(updated) {
		var dt = new Date(updated.replace(/ /, 'T')+'+09:00'),
			now = new Date(),
			diff = now.getTime() - dt.getTime(),
			ms_in_min = 60*1000,
			ms_in_hour = 60*ms_in_min,
			ms_in_day = 24*ms_in_hour,
			today = (now.getTime() + now.getTimezoneOffset()*ms_in_min) % ms_in_day;

		if(diff < ms_in_hour) {
			return this.format('{0}分前', Math.ceil(diff/ms_in_min));
		}

		if(diff < ms_in_hour*12) {
			return this.format('{0}時間前', Math.floor(diff/ms_in_hour));
		}

		if(diff < today) {
			return this.format('{0}時{1}分', dt.getHours(), dt.getMinutes());
		}
		diff -= today;

		if(diff < ms_in_day) {
			return '昨日';
		}

		if(diff < ms_in_day*5) {
			return this.format('{0}日前', Math.floor(diff/ms_in_day));
		}

		return this.format('{0}月{1}日', dt.getMonth()+1, dt.getDate());
	},

	renderUpdated: function() {
		var me = this;
		$('#hotentries .topicBody li .updated').each(function(i) {
			var newTime = me.formatUpdated(me.data[i].updated);
			newTime != $(this).text() && $(this).text(newTime);
		});
	}
};

if(location.pathname == '/home/home.jsp') {
	var widget = widgetHotEntries.create().appendTo('#bodyTable .leftContent');
	chrome.extension.sendRequest({ action: 'hotentries' }, function(json) {
		widget.find('div.topicBox').empty().append(widgetHotEntries.load(json));
	});
}

